package com.mingqijia.gassafety.console.controller.workorder;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.gap.basic.base.CommonResponse;
import com.mingqijia.gassafety.db.entity.AppealLog;
import com.mingqijia.gassafety.db.entity.HistoryAlarm;
import com.mingqijia.gassafety.db.entity.HistoryBroken;
import com.mingqijia.gassafety.shared.constant.Constants;
import com.mingqijia.gassafety.shared.utils.ApplicationUtils;
import com.mingqijia.gassafety.shared.utils.commonUtils.PageUtil;
import com.mingqijia.gassafety.webserver.request.workorder.asst.WorkOrderCreateRequest;
import com.mingqijia.gassafety.webserver.response.workorder.asst.*;
import com.mingqijia.gassafety.webserver.service.AppealLogService;
import com.mingqijia.gassafety.webserver.service.HistoryAlarmService;
import com.mingqijia.gassafety.webserver.service.HistoryBrokenService;
import com.mingqijia.gassafety.webserver.service.workorder.AsstWorkOrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.util.List;

/**
 * <p>
 * 实时状态
 *
 * @author guoliang.lao
 * @since 2022-02-18
 */

@Slf4j
@Api(tags = "工单接口")
@RestController(value = "WorkOrderController")
@RequestMapping("/business/v1/work/order/asst")
public class WorkOrderController {

    @Autowired
    AsstWorkOrderService asstWorkOrderService;
    @Autowired
    AppealLogService appealLogService;
    @Autowired
    HistoryAlarmService historyAlarmService;
    @Autowired
    HistoryBrokenService historyBrokenService;

    @ApiOperation("时刻助手创建工单")
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public CommonResponse<Object> list(@RequestBody WorkOrderCreateRequest req){
        String spId = ApplicationUtils.getWorkingSpId();
        //工单都归到报警或故障发生的企业下
        if (req.getBizType().equals(2)) {
            //报警
            HistoryAlarm historyAlarm = historyAlarmService.getById(req.getId());
            if (historyAlarm != null) {
                spId = historyAlarm.getSpId();
            }
        } else if (req.getBizType().equals(3)) {
            //故障
            HistoryBroken historyBroken = historyBrokenService.getById(req.getId());
            if (historyBroken != null) {
                spId = historyBroken.getSpId();
            }
        }
        if (req.getStatus() != 0) {
            LambdaQueryWrapper<AppealLog> queryWrapper = new LambdaQueryWrapper<>();
            if (req.getBizType().equals(2)) {
                queryWrapper.eq(AppealLog::getAlarmBrokenId,req.getId()).eq(AppealLog::getAppealType,0)
                        .eq(AppealLog::getIsDeleted,0);
            } else if (req.getBizType().equals(3)) {
                queryWrapper.eq(AppealLog::getAlarmBrokenId,req.getId()).eq(AppealLog::getAppealType,1)
                        .eq(AppealLog::getIsDeleted,0);
            }
            List<AppealLog> list = appealLogService.list(queryWrapper);
            if (!CollectionUtils.isEmpty(list)) {
                return CommonResponse.failure("已完成或处理中");
            }
        }
        //已处理
        if (req.getStatus() == 1) {
            AppealLog appealLog = new AppealLog();
            appealLog.setAlarmBrokenId(Long.parseLong(req.getId()));
            appealLog.setAppealStatus(Constants.APPEAL_STATUS_2);
            appealLog.setAppealResult(req.getAppealResult());
            appealLog.setSpId(spId);
            appealLog.setUserName(ApplicationUtils.getWorkingUser().getName());
            appealLog.setUserAccount(ApplicationUtils.getWorkingUser().getUsername());
            if (req.getBizType().equals(2)) {
                appealLog.setAppealType(0);
            } else if (req.getBizType().equals(3)) {
                appealLog.setAppealType(1);
            }
            log.info("新增时刻助手工单诉求记录："+appealLog.toString());
            appealLogService.save(appealLog);
            // 更新报警/故障信息记录主表
            if (appealLog.getAppealType() == null || appealLog.getAppealType() == 0) {
                LambdaUpdateWrapper<HistoryAlarm> historyAlarmWrapper = new LambdaUpdateWrapper<>();
                historyAlarmWrapper.eq(HistoryAlarm::getId,appealLog.getAlarmBrokenId()).eq(HistoryAlarm::getIsDeleted,0);
                HistoryAlarm historyAlarm = new HistoryAlarm();
                historyAlarm.setWorkorderId(appealLog.getWorkorderId() == null ? 0L : appealLog.getWorkorderId());
                historyAlarm.setAppealStatus(appealLog.getAppealStatus());
                historyAlarm.setAppealResult(appealLog.getAppealResult());
                historyAlarm.setUserName(appealLog.getUserName());
                historyAlarm.setUserAccount(appealLog.getUserAccount());
                historyAlarm.setAppealTime(appealLog.getCreatedAt());
                boolean historyAlarmResult = historyAlarmService.update(historyAlarm,historyAlarmWrapper);
                log.info("工单处理完成，更新报警器设备报警记录,结果：{}，内容：{}",historyAlarmResult,historyAlarm.toString());
            } else if (appealLog.getAppealType() == 1) {
                LambdaUpdateWrapper<HistoryBroken> historyBrokenWrapper = new LambdaUpdateWrapper<>();
                historyBrokenWrapper.eq(HistoryBroken::getId,appealLog.getAlarmBrokenId()).eq(HistoryBroken::getIsDeleted,0);
                HistoryBroken historyBroken = new HistoryBroken();
                historyBroken.setWorkorderId(appealLog.getWorkorderId() == null ? 0L : appealLog.getWorkorderId());
                historyBroken.setAppealStatus(appealLog.getAppealStatus());
                historyBroken.setAppealResult(appealLog.getAppealResult());
                historyBroken.setUserName(appealLog.getUserName());
                historyBroken.setUserAccount(appealLog.getUserAccount());
                historyBroken.setAppealTime(appealLog.getCreatedAt());
                boolean historyBrokenResult = historyBrokenService.update(historyBroken,historyBrokenWrapper);
                log.info("工单处理完成，更新报警器设备故障记录,结果：{}，内容：{}",historyBrokenResult,historyBroken.toString());
            }
        } else if (req.getStatus() == 2) {
            //转工单
            WorkOrderCreateRequest params = new WorkOrderCreateRequest();
            BeanUtils.copyProperties(req,params);
            params.setSpId(spId);
            Long workorderId = asstWorkOrderService.create(params);
            if (workorderId != null) {
                AppealLog appealLog = new AppealLog();
                appealLog.setWorkorderId(workorderId);
                appealLog.setAlarmBrokenId(Long.parseLong(req.getId()));
                appealLog.setAppealStatus(Constants.APPEAL_STATUS_1);
                appealLog.setSpId(spId);
                appealLog.setUserName(ApplicationUtils.getWorkingUser().getName());
                appealLog.setUserAccount(ApplicationUtils.getWorkingUser().getUsername());
                if (req.getBizType().equals(2)) {
                    appealLog.setAppealType(0);
                } else if (req.getBizType().equals(3)) {
                    appealLog.setAppealType(1);
                }
                log.info("新增时刻助手诉求记录："+appealLog.toString());
                appealLogService.save(appealLog);
                // 更新报警/故障信息记录主表
                if (appealLog.getAppealType() == null || appealLog.getAppealType() == 0) {
                    LambdaUpdateWrapper<HistoryAlarm> historyAlarmWrapper = new LambdaUpdateWrapper<>();
                    historyAlarmWrapper.eq(HistoryAlarm::getId,appealLog.getAlarmBrokenId()).eq(HistoryAlarm::getIsDeleted,0);
                    HistoryAlarm historyAlarm = new HistoryAlarm();
                    historyAlarm.setWorkorderId(appealLog.getWorkorderId() == null ? 0L : appealLog.getWorkorderId());
                    historyAlarm.setAppealStatus(appealLog.getAppealStatus());
                    historyAlarm.setAppealResult(appealLog.getAppealResult());
                    historyAlarm.setUserName(appealLog.getUserName());
                    historyAlarm.setUserAccount(appealLog.getUserAccount());
                    historyAlarm.setAppealTime(appealLog.getCreatedAt());
                    boolean historyAlarmResult = historyAlarmService.update(historyAlarm,historyAlarmWrapper);
                    log.info("工单处理完成，更新报警器设备报警记录,结果：{}，内容：{}",historyAlarmResult,historyAlarm.toString());
                } else if (appealLog.getAppealType() == 1) {
                    LambdaUpdateWrapper<HistoryBroken> historyBrokenWrapper = new LambdaUpdateWrapper<>();
                    historyBrokenWrapper.eq(HistoryBroken::getId,appealLog.getAlarmBrokenId()).eq(HistoryBroken::getIsDeleted,0);
                    HistoryBroken historyBroken = new HistoryBroken();
                    historyBroken.setWorkorderId(appealLog.getWorkorderId() == null ? 0L : appealLog.getWorkorderId());
                    historyBroken.setAppealStatus(appealLog.getAppealStatus());
                    historyBroken.setAppealResult(appealLog.getAppealResult());
                    historyBroken.setUserName(appealLog.getUserName());
                    historyBroken.setUserAccount(appealLog.getUserAccount());
                    historyBroken.setAppealTime(appealLog.getCreatedAt());
                    boolean historyBrokenResult = historyBrokenService.update(historyBroken,historyBrokenWrapper);
                    log.info("工单处理完成，更新报警器设备故障记录,结果：{}，内容：{}",historyBrokenResult,historyBroken.toString());
                }
            }
        } else {
            WorkOrderCreateRequest params = new WorkOrderCreateRequest();
            BeanUtils.copyProperties(req,params);
            params.setSpId(spId);
            asstWorkOrderService.create(params);
        }
        return CommonResponse.success(null);
    }

    @ApiOperation("查询历史工单")
    @RequestMapping(value = "/history", method = RequestMethod.GET)
    public CommonResponse<PageUtil<HistoryListResponse>> historyList(@RequestParam @ApiParam(value = "设备号") @NotNull String imei,
                                                                     @RequestParam @NotNull Integer page,
                                                                     @RequestParam @NotNull Integer pageSize){
        return CommonResponse.success(asstWorkOrderService.historyList(imei,page,pageSize));
    }

    @ApiOperation("进行中的工单")
    @RequestMapping(value = "/workingOrder", method = RequestMethod.GET)
    public CommonResponse<PageUtil<WorkingOrderListResponse>> workingOrderList(@RequestParam @ApiParam(value = "设备号")@NotNull String imei,
                                                                               @RequestParam @NotNull Integer page,
                                                                               @RequestParam @NotNull Integer pageSize){
        return CommonResponse.success(asstWorkOrderService.workingOrderList(imei,page,pageSize));
    }

    @ApiOperation(value = "查询某一天的所有班次对应剩余工作量")
    @GetMapping("/queryScheduleSurplusCount")
    public CommonResponse<List<ServicerSchedulingResponse>> queryScheduleSurplusCount(@RequestParam(name = "date") String date,
                                                                                      @RequestParam(name = "lineBizCode") String lineBizCode,
                                                                                      @RequestParam(name = "bizCode")String bizCode,
                                                                                      @RequestParam(name = "spId",required = false)String spId) {
        return CommonResponse.success(asstWorkOrderService.queryScheduleSurplusCount(date,lineBizCode,bizCode,spId));
    }

    @ApiOperation("查询业务线和业务类型")
    @RequestMapping(value = "/getBizList", method = RequestMethod.GET)
    public CommonResponse<List<BizResponse>> getBizList(@RequestParam(required = false, name = "spId")String spId) {
        return CommonResponse.success(asstWorkOrderService.getBizList(spId));
    }

    @ApiOperation("查询服务内容和服务项目")
    @RequestMapping(value = "/getServeList", method = RequestMethod.GET)
    public CommonResponse<List<BizServeResponse>> getServeList(@RequestParam(name = "pcode") @NotNull String pcode,
                                                               @RequestParam(name = "spId",required = false)String spId){
        return CommonResponse.success(asstWorkOrderService.getServeList(pcode,spId));
    }

    /**
     * 日期时间段内的每日剩余可排工作量
     * @param lineBizCode 业务线编码
     * @param bizCode 业务类型编码
     * @param startDate 开始日期
     * @param endDate 结束日期
     * @return
     */
    @ApiOperation(value = "日期时间段内的每日剩余可排工作量")
    @GetMapping("/getSurplusCountByDate")
    public CommonResponse<List<SchedulingSumCountResponse>> getSurplusCountByDate(@RequestParam(name = "lineBizCode") String lineBizCode,
                                                                                  @RequestParam(name = "bizCode") String bizCode,
                                                                                  @RequestParam(name = "startDate") String startDate,
                                                                                  @RequestParam(name = "endDate") String endDate,
                                                                                  @RequestParam(name = "spId",required = false) String spId) {
        return CommonResponse.success(asstWorkOrderService.getSurplusCountByDate(lineBizCode,bizCode,startDate,endDate,spId));
    }
}

